package com.cxb.java;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @Classname ReentrantLockZk
 * @Date 2023/4/1 14:30
 * @Created by Administrator
 * @Description TODO
 */
public class ReentrantLockZk {

    public static final String ZOOKEEPER_STRING = "127.0.0.1:2181";

    CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(ZOOKEEPER_STRING, new ExponentialBackoffRetry(1000, 3));

    public ReentrantLockZk() {
        curatorFramework.start();
    }

    /**
     * 注意：如想重入，则需要使用同一个InterProcessMutex对象。
     */
    public void checkAndLock() {
        InterProcessMutex mutex = new InterProcessMutex(curatorFramework, "/curator/lock");
        try {
            // 加锁
            boolean acquire = mutex.acquire(3, TimeUnit.SECONDS);
            if (acquire) {
                // 处理业务
                // 例如查询库存 扣减库存 模拟业务耗时
                Thread.sleep(5000);

                // 如想重入，则需要使用同一个InterProcessMutex对象
                this.testSub(mutex);

                // 释放锁
                mutex.release();
            }
        } catch (Exception e) {
            System.out.println("checkAndLock异常" + e);
        }
    }

    public void testSub(InterProcessMutex mutex) {
        try {
            boolean acquire = mutex.acquire(3, TimeUnit.SECONDS);
            if (acquire) {
                System.out.println("测试可重入锁。。。。");
                mutex.release();
            }
        } catch (Exception e) {
            System.out.println("testSub异常" + e);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(new MyTask()).start();
        }
    }
}
